package com.dylan.shot.common.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Dylan on 2017/10/21.
 */
@Configuration
@EnableCaching // 支持缓存注解
public class RedisConfig {

    @Bean(name = "myRedisTemplate")
    public RedisTemplate<String, String> getRedisTemplate(JedisConnectionFactory connectionFactory) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // RedisObjectMapper不创建为Spring管理的Bean对象,以免覆盖spring-mvc中使用的ObjectMapper对象
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer(new RedisObjectMapper()));
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }

    @Bean
    public CacheManager cacheManager(RedisTemplate<String, String> myRedisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager(myRedisTemplate);
        redisCacheManager.setDefaultExpiration(120);
        List<String> cacheNames = new ArrayList<>();
        cacheNames.add("shot");
        redisCacheManager.setCacheNames(cacheNames);
        Map<String, Long> expires = new HashMap<>();
        expires.put("shot", 120L);
        redisCacheManager.setExpires(expires);
        redisCacheManager.setUsePrefix(true);
        return redisCacheManager;
    }
}
